<template>
	<div class="merak-container-has-aside" id="zy_20240320003">
		<div class="merak-aside">
			 <treeNode @node-change="nodeChange" :defTreeValue="org_id"></treeNode>
		</div>
		<div v-waterMarker v-loading="queueLoading" class="merak-card merak-container-has-search">
			<!-- 高级搜素组件 -->
			<searchBar close-plan close-advanced custom-class="searchHeaderDaily" :placeholder="$t('clockingIn_daily.search_keyword')"  ref="searchbar" @search-event="searchBarPost">
				<template #header>
					<el-select style="width: 200px;" v-model="state.thisPageDate.office_location_id" value-key="key" clearable :placeholder="$t('clockingIn_daily.office_location')">
						<el-option v-for="oItem in workLocationArr" :key="oItem.value" :label="oItem.label"
							:value="oItem.value" />
					</el-select>
					<el-date-picker style="width: 100px;margin-left:10px;" :editable="false" v-model="state.thisPageDate.date" type="month"  :format="format" value-format="YYYY-MM" :clearable="false" @change="getStatCard" />
					
				</template>
			</searchBar>
			<!-- 统计筛选组件 -->
			<!-- <div class="deailyNav">
				<MerakStatCard v-model="state.statValue" :data="state.statData" @change="handleStatChange" />
			</div> -->
			<!-- 表格组件 -->
			<div class="merak-table-wrapper">
				<MerakXTable v-bind="tablePayload" :batch-click="handleBatchClick" :handler-click="handleHanderClick"
					:query-columns="queryColumns" :query-data="queryData">
					<!-- <template #employee_details_head="{ column }">
						<div class="employee_details_head">
							{{column.title}}
						</div>
					</template> -->
					<template #employee_details="{ row }">
						<div class="user_box">
							<!-- <img :src="row.avatar"/> -->
							<div class="user_name">{{row.employee_name}}</div>
						</div> 
					</template>
				</MerakXTable>
			</div>
		</div>
	</div>
</template>

<!-- render 函数需要设置为 jsx 语法 -->
<script setup lang="tsx" name="attendanceSummary">
	import {
		reactive,
		computed,
		watch,
		onMounted,
		ref,
		getCurrentInstance
	} from "vue";

	import {
		ElButton,
		ElPopover
	} from "element-plus";
	import treeNode from '@/views/personalManagement/a-components/oragnizationTree/index.vue';
	import searchBar from "@/components/SearchBar";
	import merakColapse from "@/components/merakColapse/index.vue";
	import selectedParams from "@/components/SearchBar/components/selectedParams.vue";
	import MerakStatCard, {
		MerakStatCardInstance,
		MerakStatDataType
	} from "@/components/MerakStatCard";
	import MerakXTable, {
		MerakXTableInstance,
		MerakXTableProps
	} from "@/components/MerakXTable";
	import { getDictOptions} from "@/api/modules/sysManage/personnel";
	import useLoading from "@/hooks/useLoading";
	import useDateFormat from "@/hooks/useDateFormat";
	import router from "@/routers";
	
	import {
		ResultEnum
	} from "@/enums/httpEnum";
	import {
		Path,
		getTableColumns,
		getTableData
	} from "@/api/modules/table";
	import {
		getCheckingInTabs,getCheckingInTableHeader,getCheckingInMonthTableData,getLocationSelect
	} from "@/api/modules/personalManagementApi/checkingIn";
	import { getLocationParams } from "@/utils/index";
	
	const format = useDateFormat().renderFormat("YYYY-MM");
	console.log(format)
	const { proxy } = getCurrentInstance()!;
	// 使用队列 loading 管理初始化页面加载状态
	const {
		queueLoading,
		queueId
	} = useLoading();
	
	const formattedDate = () => {
		const today = new Date();
		let year = today.getFullYear();
		let month = (today.getMonth() + 1).toString().padStart(2, '0');
		if(Number(month) === 1){
			year = Number(year)-1
			month = 12
		} else {
			month = Number(month)-1
		}
		if(month<=9){
			month = '0'+month
		}
		console.log('我的月')
		console.log(month)
		return `${year}-${month}`;
	}
	const org_id=ref("")
	const nodeChange = (menuItem) =>{
		state.thisPageDate.org_id = menuItem.org_id;
		
		const newUrl = new URL(window.location.href);
		//console.log(newUrl)
		newUrl.searchParams.set('org_id', menuItem.org_id);
		org_id.value= menuItem.org_id;
		// 使用pushState更新浏览器历史记录
		window.history.pushState({}, '', newUrl.toString());
		
		state.thisPageDate.org_id = menuItem.org_id;
		queryStatData()
	}
	const getStatCard = dateValue =>{
		queryStatData()
	}
	// 页面配置数据
	const state = reactive < {
		filterOptions: Array < any > ;
		statValue: string;
		statData: MerakStatDataType[][];
		statParams: Record < string,string > ;
		thisPageDate : Record < string,string > ;
	} > ({
		// 高级搜索方案下拉选项
		filterOptions: [],
		// 统计筛选激活项
		statValue: "",
		// 统计筛选数据
		statData: [],
		// 统计筛选激活后筛选数据
		statParams: {},
		thisPageDate:{
			keyword:"",
			org_id:"0",
			date:formattedDate(),
			type:"0",
			advanced:{},
			office_location_id:'',
		},
		
	});

	// 动态计算表格的外部筛选数据
	const params = computed(() => ({
		...state.statParams,
		...state.thisPageDate
	}));
	
	// 表格配置属性
	const tablePayload = reactive < MerakXTableProps > ({
		// 列设置存储的数据对照值
		columnsByStore: [],
		// 表格行数据的唯一 key, 跟后端同步
		rowKey: "user_id",
		// 初始化的外部筛选数据
		params,
		// 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
		// ["selection", { type: 'handle', width: 200, slot: 'custom_slot_name' | ({ row })=> Component }]
		//columnType: ["selection"],
		// 批量操作选项
		// batches: [{
		// 	type: "delete",
		// 	text: "批量删除",
		// 	color: "red"
		// }],
		// 操作列选项
		// handles: [{
		// 	type: "delete",
		// 	text: "删除",
		// 	color: "red"
		// }]
	});

	// 统计筛选激活触发 table 数据请求
	const handleStatChange: MerakStatCardInstance["onChange"] = params => {
		console.log(params)
		if(params.type){
			state.thisPageDate.type = params.type;
		} else {
			state.thisPageDate.type = "0";
		}
		
	};

	/**
	 * 表格批量操作事件触发
	 * @param type 同 tablePayload.batched 子项的 type
	 * @param mode 表格选中的模式  current: 当前页  all: 所有页
	 * @param selectedKeys 表格当前页选中模式下选中的行数据 key 的集合, 表格所有页选中模式下未选中的行数据 key 的集合
	 */
	const handleBatchClick: MerakXTableInstance["batchClick"] = async ({
		type,
		mode,
		selectedKeys
	}) => {
		switch (type) {
			case "delete":
				return {
					// 是否刷新表格, 默认 false, 可选参数
					refresh: false,
						// 是否重置表格(分页、排序), 默认 false, 可选参数
						reset: false
				};
			default:
				return;
		}
	};

	/**
	 * 表格操作列事件触发
	 * @param type 同 tablePayload.handles 子项的 type
	 * @param params 表格操作数据, 可结构关于操作行的数据 { row, rowIndex, rowId }
	 */
	const handleHanderClick: MerakXTableInstance["handlerClick"] = async ({
		type,
		params
	}) => {
		switch (type) {
			case "delete":
				// 是否刷新表格, 默认 false, 可选参数
				return true;
			default:
				return;
		}
	};
	
	const queryOptions = async (key: string, parent_id?: string | number) => {
	  return await getDictOptions({ key, parent_id }, queueId.value).then(({ code, data }) => {
	    if (code == ResultEnum.SUCCESS) {
	      return data;
	    }
	  });
	};
	// 获取统计数据
	const queryStatData = async () => {
		// 初始化接口需要传入队列 loading 暴露的 id
		let getData = {...state.thisPageDate};
		getData.type = "MonthStatisticsList";
		return getCheckingInTabs(getData).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				data = {
					one:data
				}
				state.statData = Object.values(data).map(item => item);
				//console.log(state.statData)
			}
		});
	};

	
	// 获取表头数据
	const queryColumns: MerakXTableInstance["queryColumns"] = async () => {
		// 初始化接口需要传入队列 loading 暴露的 id
		let columnsData = {
			type:'MonthStatisticsList'
		}
		if(state.thisPageDate.date != ''){
			columnsData.date = state.thisPageDate.date
		}
		return getCheckingInTableHeader(columnsData).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				// 克隆表头数据作为列设置的对照数据
				tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
				return {
					...data,
					columns: [...data.columns].map(column => {
						switch (column.field) {
							case "year_month":
								column.fixed = "left";
								column.width = "120px";
								return column;
							case "employee_name":
								column.fixed = "left";
								column.width = "140px";
								column.slots = {
									//header:"employee_details_head",
									default: "employee_details"
								};
								return column;
							default:
								return column;
						}
					})
				};
			}
		});
	};

	/**
	 * 获取表格数据
	 * @param page 分页参数
	 * @param sorts 多重排序参数
	 * @param filters 表头筛选参数
	 * @param from 外部由 tablePayload.params 传入的自定义参数
	 */
	const queryData: MerakXTableInstance["queryData"] = async ({
		page,
		sorts,
		from
	}) => {
		// 创建请求表格数据的参数
		const params: Record < string, any > = {};
		// 如果有分页数据
		if (!!page) {
			Object.assign(params, {
				...page
			});
		}
		// 如果有排序数据
		if (!!sorts) {
			for (let sort of sorts.values()) {
				console.log(sort);
			}
		}
		// 如果有自定义参数
		if (!!from) {
			for (let key of Object.keys(from)) {
				const item = from[key];
				!!item && (params[key] = item);
			}
		}
		// 初始化接口需要传入队列 loading 暴露的 id
		return getCheckingInMonthTableData(params).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				
				return data.table_data;
			}
		});
	};
	//工作地点数组
	const workLocationArr = ref([]);
	const getWorkLocation = () => {
		getLocationSelect().then(({ code, data }) => {
		  if (code == 2000) {
				data.map(e=>{
					e.label = e.value;
					e.value = e.key;
				})
				workLocationArr.value = data;
		  }
		});
	}
	// 初始化页面
	const init = async () => {
		queryFilterOptions();
		queryStatData();
		getWorkLocation()
	};

	// 监听初始化队列 loading 状态
	watch(queueLoading, () => {
		if (queueLoading.value) {
			// 页面初始化队列 loading 时不允许 table 自动 loading
			tablePayload.loading = false;
		} else if ("loading" in tablePayload) {
			// 队列 loading 完成后清除 table 受控的 loading 属性
			delete tablePayload.loading;
		}
	});

	// 运行初始化
	onMounted(() => {
		const newUrl = new URL(window.location.href);
		let url_org_id = getLocationParams(newUrl.href,'org_id');
		org_id.value=url_org_id;
		if(url_org_id !== false){
			state.thisPageDate.org_id = url_org_id;
		}
		init();
		// //岗位
		// queryOptions("org_title").then(options => {
		// 	let newoptions = [];
		// 	options.map(e=>{
		// 		newoptions.push({
		// 			label:e.value,
		// 			value:e.key
		// 		})
		// 	}) 
		// 	searchform.value.org_title.options = newoptions ?? [];
		// });
		// //工作性质
		// queryOptions("job_nature").then(options => {
		// 	let newoptions = [];
		// 	options.map(e=>{
		// 		newoptions.push({
		// 			label:e.value,
		// 			value:e.key
		// 		})
		// 	}) 
		// 	searchform.value.job_nature.options = newoptions ?? [];
		// });
		// //证件类型
		// queryOptions("id_type").then(options => {
		// 	let newoptions = [];
		// 	options.map(e=>{
		// 		newoptions.push({
		// 			label:e.value,
		// 			value:e.key
		// 		})
		// 	}) 
		// 	searchform.value.id_type.options = newoptions ?? [];
		// });
	});
	
	// 获取高级搜索方案
	const queryFilterOptions = async () => {
		searchbar.value.getPlanList('MonthStatisticsList');
		// 初始化接口需要传入队列 loading 暴露的 id
	};
	
	// 高级搜索表单
	const ruleFormRef = ref < FormInstance > ();
	const searchform = ref({
		org_title: {
			label: proxy!.$t("clockingIn_daily.position"),
			value: "",
			type: "select",
			options: []
		},
		job_nature: {
			label:proxy!.$t("clockingIn_daily.job_category"),
			value: "",
			type: "select",
			options: []
		},
		hiredate: {
			label: proxy!.$t("clockingIn_daily.date_on_board"),
			value: "",
			type: "date",
		},
		id_type: {
			label: proxy!.$t("clockingIn_daily.certificate_type"),
			value: "",
			type: "select",
			options: []
		},
		id_no: {
			label: proxy!.$t("clockingIn_daily.id_number"),
			value: "",
			type: "input",
		},
	});
	
	//高级搜索模态
	const searchbar = ref();
	
	
	
	
	//点击取消按钮关闭高级搜索模态框
	const closeModal = () => {
		searchbar.value.modalHide();
		searchbar.value.clear();
	};
	
	//打开搜索方案弹出
	const showPlanModal = () => {
		searchbar.value.showPlanModal();
	};
	
	//搜索表单提交
	const searchSubmitForm = async (formEl: FormInstance | undefined) => {
		state.thisPageDate.advanced = {
			...searchbar.value.formParams("value")
		};
		searchbar.value.clear();
		searchbar.value.modalHide();
		queryStatData()
	};
	
	
	//触发了快速搜索或者搜索方案
	const searchBarPost = params => {
		//console.log(params)
		let postParams = {
			...params.params,
		};
		state.thisPageDate.keyword = params.search;
		state.thisPageDate.advanced = postParams;
		queryStatData()
	};
</script>

<style lang="scss" scoped>
	@import "./index.scss";
</style>